package com.lee.mq.mqserver;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-10-29
 * Time: 18:27
 */

import com.lee.mq.common.*;
import com.lee.mq.mqserver.core.BasicProperties;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BrokerServer 就是咱们 消息队列 本体服务器.
 * 本质上就是一个 TCP 的服务器.
 * BrokerServer 是最核⼼的部分. 负责消息的存储和转发.
 */
public class BrokerServer {
    // 创建一个服务端Socket
    private ServerSocket serverSocket = null;
    // 当前暂不考虑一个BrokerServer有多个VirtualHost的情况
    // 只考虑一个BrokerServer只有一个VirtualHost的情况
    private VirtualHost virtualHost = new VirtualHost("default");
    // 创建一个会话哈希表，存储与服务器通信的 channel. String 表示channelId；value 表示对应的 Socket 对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    // 创建一个线程池用于处理多个客户端之间的请求
    private ExecutorService executorService = null;
    // 创建一个 boolean 变量控制服务器是否继续运行
    private volatile boolean runnable = true;

    // 构造方法，初始化BrokerServer的端口号
    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    // 启动方法
    public void start() throws IOException {
        System.out.println("[BrokerServer] 服务器启动!");
        executorService = Executors.newCachedThreadPool();

        try {
            while (runnable) {
                // 获取到客户端的连接
                Socket clientSocket = serverSocket.accept();
                // 将处理连接的逻辑丢给线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            // 这个异常一般在连接关闭是触发
            System.out.println("[BrokerServer] 服务器停止!");
        } finally {
            // 关闭连接，释放资源
            stop();
        }
    }

    // 这个方法用于处理一个客户端连接，一个客户端连接可能涉及到多个请求/响应
    private void processConnection(Socket clientSocket) {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            try(DataInputStream dataInputStream = new DataInputStream(inputStream);
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    // 1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    // 2.根据请求构造响应
                    Response response = process(request,clientSocket);
                    // 3.将响应写回到客户端
                    writeResponse(dataOutputStream,response);
                }
            }
        } catch (EOFException | SocketException e) {
            // DataInputStream 如果读到 EOF , 就会抛出一个 EOFException 异常.需要借助这个异常来结束循环
            System.out.println("[BrokerServer] connection 关闭! 客户端的地址: " + clientSocket.getInetAddress().toString()
                    + ":" + clientSocket.getPort());
        } catch (IOException | MqException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                // 关闭客户端socket
                clientSocket.close();
                // 关闭对应的channel
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearClosedSession(Socket clientSocket) {
        // 存放待删除结点
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String,Socket> channel: sessions.entrySet()) {
            // 不可以一遍遍历一边删除，将待删除结点记录下来，后续统一删除
            if (channel.getValue() == clientSocket) {
                toDeleteChannelId.add(channel.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成! 被清理的 channelId=" + toDeleteChannelId);
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException, MqException {
        Request request = new Request();
        // 读取4个字节的请求类型
        int type = dataInputStream.readInt();
        // 读取4个字节的载荷长度
        int length = dataInputStream.readInt();
        // 读取length的载荷
        byte[] payload = new byte[length];
        int actualLen = dataInputStream.read(payload);
        if (actualLen != length) {
            throw new MqException("[BrokerServer] 读取请求格式错误.");
        }
        request.setType(type);
        request.setLength(length);
        request.setPayload(payload);
        return request;
    }

    // 加锁测试
    synchronized private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
//        System.out.println("载荷长度:"+response.getLength());
        dataOutputStream.write(response.getPayload());
        // 刷新缓冲区
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        // 1.对payload做一个初步解析（解析为BasicArgument，后续根据具体情况转为对应子类）
        BasicArguments basicArgumets = (BasicArguments) BinaryTool.toObject(request.getPayload());
        System.out.println("[Request]初步解析：" +"type = "+ request.getType()+",length = "+request.getLength()
                +",rid = "+basicArgumets.getRid()+",channelId = "+basicArgumets.getChannelId());
        // 2.根据请求类型对请求进行下一步处理
        boolean ok = true;
        if (request.getType() == 0x1) {
            // (1)创建channel
            sessions.put(basicArgumets.getChannelId(),clientSocket);
            System.out.println("[BrokerServer] 创建完成: channelId = "+basicArgumets.getChannelId());
        } else if (request.getType() == 0x2) {
            // (2)销毁channel
            sessions.remove(basicArgumets.getChannelId());
            System.out.println("[BrokerServer] 销毁完成: channelId = "+basicArgumets.getChannelId());
        } else if (request.getType() == 0x3) {
            // (3)创建exchange
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArgumets;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getExchangeType(),
                    arguments.isDurable(),arguments.isAutoDelete(),arguments.getArguments());
        } else if (request.getType() == 0x4) {
            // (4)销毁exchange
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArgumets;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // (5)创建queue
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArgumets;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isExclusive(),
                    arguments.isAutoDelete(),arguments.getArguments());
        } else if (request.getType() == 0x6) {
            // (6)销毁queue
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArgumets;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // (7)创建binding
            QueueBindArguments arguments = (QueueBindArguments) basicArgumets;
            ok = virtualHost.queueBind(arguments.getExchangeName(),arguments.getQueueName(),arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // (8)销毁binding
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArgumets;
            ok = virtualHost.queueUnbind(arguments.getExchangeName(),arguments.getQueueName());
        } else if (request.getType() == 0x9) {
            // (9)发送message
            BasicPublishArguments arguments = (BasicPublishArguments) basicArgumets;
            ok = virtualHost.basicPublish(arguments.getExchangeName(),arguments.getRoutingKey(),
                    arguments.getBasicProperties(),arguments.getBody());
        } else if (request.getType() == 0xa) {
            // (10)订阅message
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArgumets;
            ok = virtualHost.basicCosume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                    // 这个回调函数是写死的，主要功能是将消息推送给订阅者客户端
                    // (1)这里的consumerTag是订阅者的channelId，根据channelId找到对应的订阅者socket
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅者客户端异常.");
                    }
                    // (2)构造响应数据payload
                    SubScribeReturns subScribeReturns = new SubScribeReturns();
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(basicProperties);
                    subScribeReturns.setBody(body);
                    subScribeReturns.setRid(""); // 由于这里只有响应没有请求，所以这里的rid无意义
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setOk(true);
                    // 转为字节数组
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
//                    System.out.println("消息载荷长度为:"+payload.length);
                    // (3)将响应写回给订阅者客户端
                    Response response = new Response();
                    response.setType(0xc);
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    // 这里流对象不能关闭，因为要持续写入数据
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());

                    // ------------------------------------ 这里重点理解 -------------------------------------------
//                    synchronized (this) {
                    writeResponse(dataOutputStream,response);
//                    }
                }
            });
        } else if (request.getType() == 0xb) {
            // (11)返回ACK
            BasicAckArguments arguments = (BasicAckArguments) basicArgumets;
            ok = virtualHost.basicAck(arguments.getQueueName(),arguments.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 未知 type: "+request.getType());
        }

        // 3.构造响应(BUG001,先构造载荷在设置response中的length)
        // 构造载荷
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setRid(basicArgumets.getRid());
        basicReturns.setChannelId(basicArgumets.getChannelId());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);

        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] type = "+response.getType()+",length = "+response.getLength()+
                ",rid = "+basicReturns.getRid()+",channelId = "+basicReturns.getChannelId());
        return response;
    }

    // 一般来说停止服务器, 就是直接 kill 掉对应进程就行了.
    // 此处还是搞一个单独的停止方法. 主要是用于后续的单元测试.
    public void stop() throws IOException {
        runnable = false;
        // 把线程池中的任务都放弃了. 让线程都销毁.
        executorService.shutdownNow();
        serverSocket.close();
    }
}
